<?php

namespace app\system\controller\logic;

use app\common\model\FieldLogic;
use app\common\model\FieldModel;
use app\common\model\logic\CarDriverModel;
use app\common\model\logic\CarLeaveModel;
use think\Cache;
use think\Db;
use think\Request;

class QueryController extends \app\system\controller\BaseController
{

    private $mid;
    private $moudleCache;
    private $moudleName;
    private $fieldModel;
    private $fieldLogic;
    private $opModel;
    private $tableName;

    /**
     * 初始化
     */
    public function __construct(Request $request)
    {
        parent::__construct($request);
        $this->mid = $this->request->param('mid/d', 0);
        $this->moudleCache = Cache::get('moudle');
        $this->fieldModel = new FieldModel();
        if ($this->mid > 0) {
            $this->opModel = cms_moudle($this->mid);
            $this->moudleName = $this->moudleCache[$this->mid]['moudle_name'];
            $this->tableName = $this->moudleCache[$this->mid]['table_name'];
            $this->fieldLogic = new FieldLogic($this->tableName);
        }
    }

    /**
     * 获取行车单数量
     */
    public function getOrderCount(){
        $driverId = Db::table('car_driver')->where('bind_uid',$this->getUid())->value('aid');
        //指定驾驶员
        if($this->request->param('driver')){
            $string="find_in_set('{$driverId}',fleet_driver_ids)"; //指定的驾驶员
        }else{
            $string="1=1";
        }
        //即将开始
        $q1['car_status']=0;
        $q1['order_start_time']=['>',time()];
        //正在进行
        $q2['car_status']=1;
        //$q2['order_start_time']=['<',time()];
        //$q2['order_end_time']=['>',time()];
        //已结束
        $q3['car_status']=2;
        /*有未确认的订单*/
        $q4['order_confirm']=['not like','%"'.$driverId.'"%'];
        $q4['car_status']=0;
        $s['q1'] = cms_moudle(14)->where($string)->where($q1)->count();
        $s['q2'] = cms_moudle(14)->where($string)->where($q2)->count();
        $s['q3'] = cms_moudle(14)->where($string)->where($q3)->count();
        $s['q4'] = cms_moudle(14)->where($string)->where($q4)->count();
        return $s;
    }

    /**
     * 异常请假
     */
    public function badleave(){
        $dri_ids = $this->request->param('dri_ids');
        $carLeaveModel = new CarLeaveModel();
        $carDriverModel = new CarDriverModel();
        $uids = $carDriverModel->where('aid','in',$dri_ids)->column('bind_uid');
        $list = $carLeaveModel->where('last_time>0')->where('leave_end_time','>',time())->limit(10)->where('leave_uid','in',$uids)->select();
        $data['rows'] = $list;
        return $data;
    }
    /**
     * 车辆列表
     * @return mixed
     */
    public function carList(){
        $pageSize = $this->request->param('pageSize/d');
        $pageNumber = $this->request->param('pageNumber/d');
        //排序
        $sortName = $this->request->param('sortName/s');
        $sortOrder = $this->request->param('sortOrder/s');
        if(!empty($sortName) && !empty($sortOrder)){
            $order="{$sortName} {$sortOrder}";
        }else{
            $order="sort desc";
        }
        $where['mid'] = $this->mid;
        //检索车牌号
        $carSn = $this->request->param('car_sn');
        if(!empty($carSn)) $where['car_sn'] = ['like','%'.$carSn.'%'];
        //检索状态
        $carStatus = $this->request->param('car_status/d');
        if($carStatus>=0) $where['car_status'] = $carStatus;
        $map = $this->opModel->getExtendMap($this->request->request());
        $op = $this->getOp();
        $map = array_merge($where,$map,$op);
        try{
            $total = $this->opModel->where($map)->count(); //检索过后的条数
            if($total==0){
                exception('未检索到数据！',40001);
            }
            $list = $this->opModel->field(true)->where($map)->order($order)->page($pageNumber,$pageSize)->select();
            foreach ($list as $k=>$v){
                //0未指派 1已指派 2出发中 3已收车
                $list[$k]['btype_name']=get_field_value('car_btype','title',['aid'=>$v['btype_aid']]);
                $list[$k]['last_order_time']=cms_moudle(14)->where(['car_sn'=>$v['car_sn'],'car_status'=>2])->order('back_time desc')->value('back_time');
                $list[$k]['soon_order_time']=cms_moudle(14)->where(['car_sn'=>$v['car_sn'],'car_status'=>1])->order('order_start_time asc')->value('order_start_time');
                if(!empty( $list[$k]['last_order_time'])){
                    $list[$k]['last_order_time']=date('Y-m-d h:i',$list[$k]['last_order_time']);
                }
                if(!empty($list[$k]['soon_order_time'])){
                    $list[$k]['soon_order_time']=date('Y-m-d h:i',$list[$k]['soon_order_time']);
                }
                $list[$k]['car_status_text']=$v['car_status_text'];
                $list[$k]['service_status']=get_field_value('car_service','service_status',['car_id'=>$v['aid']]);
            }
            $data['total'] = $total;
            $data['rows'] = $list;
            $data['sql'] = $this->opModel->getLastSql();
            return $data;
        }catch (\Exception $e){
            $data['total'] = 0;
            $data['rows'] = [];
            return $data;
        }
    }

    /**
     * 司机订单列表
     * @return mixed
     */
    public function driverOrder(){
        $pageSize = $this->request->param('pageSize/d');
        $pageNumber = $this->request->param('pageNumber/d');
        //排序
        $sortName = $this->request->param('sortName/s');
        $sortOrder = $this->request->param('sortOrder/s');
        if(!empty($sortName) && !empty($sortOrder)){
            $order="{$sortName} {$sortOrder}";
        }else{
            $order="sort desc";
        }
        $where['mid'] = $this->mid;
        if(!$this->request->has('data_type')){
            $driverId = Db::table('car_driver')->where('bind_uid',$this->getUid())->value('aid');
            $string="find_in_set('{$driverId}',fleet_driver_ids)"; //指定的驾驶员
        }else{
            $driverId=-1;
        }
        $orderType = $this->request->param('order_type/d',1);
        switch ($orderType){
            case 0: //司机未确认订单
                if($driverId!=-1){
                    $where['order_confirm']=['not like','%"'.$driverId.'"%'];
                }
                break;
            case 1: //即将开始
                if($driverId!=-1) {
                    $where['order_confirm'] = ['like', '%"' . $driverId . '"%'];
                }
                $where['car_status']=0;
                //$where['order_start_time']=['>',time()];
                break;
            case 2: //正在进行
                /*
                $where['order_start_time']=['<',time()];
                $where['order_end_time']=['>',time()];
                */
                $where['car_status']=1;
                break;
            case 3: //已结束
                $where['car_status']=['>=',2];
                //$where['order_end_time']=['<',time()];
                break;
        }
        $map = $this->opModel->getExtendMap($this->request->request());
        $op = $this->getOp();
        $map = array_merge($where,$map,$op);
        try{
            $total = $this->opModel->where($map)->count(); //检索过后的条数
            if($total==0){
                $data['total'] = 0;
                $data['rows'] = [];
                return $data;
            }
            $list = $this->opModel->field(true)->where($map)->order($order)->where($string)->page($pageNumber,$pageSize)->select();
            $data['total'] = $total;
            $data['rows'] = $list;
            $data['sql'] = $this->opModel->getLastSql();
            return $data;
        }catch (\Exception $e){
            $this->error($e->getMessage());
        }
    }
	
	

    //请假记录 违章记录 维修记录 保养记录 事故记录
    public function record(){
        $pageSize = $this->request->param('pageSize/d');
        $pageNumber = $this->request->param('pageNumber/d');
        //排序
        $sortName = $this->request->param('sortName/s');
        $sortOrder = $this->request->param('sortOrder/s');
        if(!empty($sortName) && !empty($sortOrder)){
            $order="{$sortName} {$sortOrder}";
        }else{
            $order="aid desc";
        }
        $where['mid'] = $this->mid;
        switch ($this->mid){
            case '9': //事故记录
                $actionUid = 'accident_driver';
                break;
            case '10': //违章记录
                $actionUid = 'break_driver';
                break;
            case '12': //请假记录
                $actionUid = 'leave_uid';
                break;
            case '15': //维修保养
                $actionUid = 'ser_user';
                break;
        }
        $where[$actionUid]=$this->getUid();

        if($this->mid=='12'){
            $leaveStatus = $this->request->param('leave_status/d',0);
            $where['leave_status'] = $leaveStatus;
        }
        if($this->mid=='15'){
            //0|保养,1|维修
            $serType = $this->request->param('ser_type/d',0); //保养记录
            $where['ser_type'] = $serType;
        }
        $map = $this->opModel->getExtendMap($this->request->request());
        $op = $this->getOp();
        $map = array_merge($where,$map,$op);
        try{
            $total = $this->opModel->where($map)->count(); //检索过后的条数
            if($total==0){
               exception('未检索到数据！',40001);
            }
            $list = $this->opModel->field(true)->where($map)->order($order)->page($pageNumber,$pageSize)->select();
            $list = $this->opModel->formatList($list);
            foreach($list as $k=>$v){
                if($this->mid=='12'){
                    $list[$k]['leave_status_text'] = $v['leave_status_text'];
                }
            }
            $data['total'] = $total;
            $data['rows'] = $list;
            $data['sql'] = $this->opModel->getLastSql();
            return $data;
        }catch (\Exception $e){
            $data['total'] = 0;
            $data['rows'] = [];
            return $data;
        }
    }

    /**
 * 添加/更新记录
 * */
    public function infoRecord(){
        try{
            $data=$this->request->param();
            if(array_key_exists('driver_uid',$data)){
                $data['aid']=get_field_value('car_driver','aid',['bind_uid'=>$data['driver_uid']]);
            }
            if($data['is_update']==1){
                cms_moudle($data['mid'])->isUpdate(true)->allowField(true)->save($data);
            }else{
                cms_moudle($data['mid'])->allowField(true)->save($data);
            }
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }
        $this->success('操作成功！');
    }
	//反写车辆
	public function upcar(){
		$data=$this->request->param();
		cms_moudle(5)->isUpdate(true)->allowField(true)->save($data);
		$this->success('操作成功');
	}
    /**
     * 获取多条记录
     */
    public function getList(){
        $data=$this->request->param();
        $list=cms_moudle($data['mid'])->where('aid','in',$data['aid'])->select();
        return $list;
    }
    /**
     * 获取保险列表
     * @return mixed
     */
    public function safeList(){
        $pageSize = $this->request->param('pageSize/d');
        $pageNumber = $this->request->param('pageNumber/d');
        //排序
        $sortName = $this->request->param('sortName/s');
        $sortOrder = $this->request->param('sortOrder/s');
        if(!empty($sortName) && !empty($sortOrder)){
            $order="{$sortName} {$sortOrder}";
        }else{
            $order="sort desc";
        }
        $where['mid'] = $this->mid;
        //检索车牌号
        $carSn = $this->request->param('car_sn');
        if(!empty($carSn)) $where['car_sn'] = ['like','%'.$carSn.'%'];
        //检索状态
        $map = [];
        $op = $this->getOp();
        $map = array_merge($where,$map,$op);
        try{
            $total = $this->opModel->where($map)->count(); //检索过后的条数
            if($total==0){
                exception('未检索到数据！',40001);
            }
            $list = $this->opModel->field(true)->where($map)->order($order)->page($pageNumber,$pageSize)->select();
            foreach ($list as $k=>$v){
                $time=time();
                $list[$k]['surplus']=ceil((strtotime($v['safe_endtime'])-$time)/86400);
                $list[$k]['car_sn_text']=get_field_value('car','car_sn',['aid'=>$v['car_sn']]);
            }
            $data['total'] = $total;
            $data['rows'] = $list;
            $data['sql'] = $this->opModel->getLastSql();
            return $data;
        }catch (\Exception $e){
            $data['total'] = 0;
            $data['rows'] = [];
            return $data;
        }
    }
    /*添加保险信息*/
    public function addSafe(){
        try{
            $data=$this->request->param();
            $safeInfo=cms_moudle(13)->where(['safe_year'=>$data['safe_year'],'car_sn'=>$data['car_sn']])->find();
            if($safeInfo){
                $this->error('本年度的保险已经添加，如需更改请选择编辑');
                return false;
            }else{
                $result= cms_moudle(13)->isUpdate(false)->allowField(true)->save($data);
                if($result){
                    cms_moudle(13)->where(['safe_year'=>$data['safe_year']-1,'car_sn'=>$data['car_sn']])->setField('is_renewal',1);
                }
            }
        }catch (\Exception $e) {
            $this->error($e->getMessage());
        }
        $this->success('操作成功！');
    }
    /**
     * 获取请假列表
     * @return mixed
     */
    public function leaveList(){
        $pageSize = $this->request->param('pageSize/d');
        $pageNumber = $this->request->param('pageNumber/d');
        //排序
        $sortName = $this->request->param('sortName/s');
        $sortOrder = $this->request->param('sortOrder/s');
        if(!empty($sortName) && !empty($sortOrder)){
            $order="{$sortName} {$sortOrder}";
        }else{
            $order="sort desc";
        }
        $where['mid'] = $this->mid;
        //检索状态
        $map = [];
        $leave_status=$this->request->param('leave_status');
        if($leave_status>-1){
           $map['leave_status']=$leave_status;
        }
        $op = $this->getOp();
        $map = array_merge($where,$map,$op);
        try{
            $total = $this->opModel->where($map)->count(); //检索过后的条数
            if($total==0){
                exception('未检索到数据！',40001);
            }
            $list = $this->opModel->field(true)->where($map)->order($order)->page($pageNumber,$pageSize)->select();
            foreach ($list as $k=>$v){
                $list[$k]['driver_name']=get_field_value('car_driver','title',['bind_uid'=>$v['leave_uid']]);
            }
            $data['total'] = $total;
            $data['rows'] = $list;
            $data['sql'] = $this->opModel->getLastSql();
            return $data;
        }catch (\Exception $e){
            $data['total'] = 0;
            $data['rows'] = [];
            return $data;
        }
    }
    /*获取车辆的实时状态*/
    public function getCarstatus(){
        $carId=$this->request->param('car_id');
        $carStatus=get_field_value('car','car_status',['aid'=>$carId]);
        return $carStatus;
    }
    /**
     * 车辆信息统计
    */
    public function carInfo(){
        $data['num1']=cms_moudle(5)->where('btype_aid',1)->count();//自有车辆
        $data['num2']=cms_moudle(5)->where('btype_aid','gt',1)->count();//其他车辆
        $data['num3']=cms_moudle(5)->where('car_status',0)->count();//可用
        $data['num4']=cms_moudle(5)->where('car_status',1)->count();//出车
        $data['num5']=cms_moudle(5)->where('car_status',2)->count();//维修
        $data['num5']=cms_moudle(5)->where('car_status',3)->count();//保养
        return $data;
    }
}

